$(function(){
	var ws = null;
	var ws_url = "ws://wpfc.gitee.io/websocket/chat";
//	var ws_url = "ws://localhost:8080/chat";
	var lockReconnect = false;//避免重复连接
	var heartCheck = null; 
	var cur_rname = "公共场所";
	var cur_rpsw = "";
	var sel_userid = "";   //私聊对象
	
	heartCheck = {
	    timeout: 60000,//60ms
	    timeoutObj: null,
	    serverTimeoutObj: null,
	    reset: function(){
	        clearTimeout(this.timeoutObj);
	        clearTimeout(this.serverTimeoutObj);
			this.start();
	    },
	    start: function(){
	        var self = this;
	        this.timeoutObj = setTimeout(function(){
	            sendJson("heart", "");
	            /*self.serverTimeoutObj = setTimeout(function(){
	                //如果onclose会执行reconnect，我们执行ws.close()就行了.
	            	//如果直接执行reconnect 会触发onclose导致重连两次
	                ws.close();
	            }, self.timeout)*/
	        }, this.timeout)
	    },
	    stop: function(){
	    	clearTimeout(this.timeoutObj);
	        clearTimeout(this.serverTimeoutObj);
	    }
	};
	
	$("#connect").bind("click", function(){
		connect();
	});
	
	function connect(){
		if(checkURL()){
			$("#connect").addClass("btn-default").attr("disabled", true);
			initWebSocket();
		}
	}
	
	$("#disconnect").bind("click", function(){
		if(ws != null){
			ws.close();
			heartCheck.stop();
			$(".send").hide();
			$(".connect").show();
			$(".footer").html("wpfc")
		}else{
			layer.msg('请先来连接服务器!');
		}
	});
	
	$("#send").bind("click", function(){
		sendMessage();
	});
	
	$("input[name=content]").keypress(function(e){
        var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if (eCode == 13){
        	sendMessage();
        }
	});
	
	$("input[name=url]").keypress(function(e){
        var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if (eCode == 13){
        	connect();
        }
	});
	
	function sendMessage(){
		if(checkContent()){
			var content = $.trim($("input.content").val());
			sel_userid ? sendJson("one", content, sel_userid) : sendJson("all", content);
			printSelf(content);
			$("input.content").val("");
		}
	}
	
	function checkContent(){
		var content = $.trim($("input.content").val());
		if(!content){
			layer.msg('请输入发送的内容!');
			return false;
		}
		return true;
	}
	
	function checkURL(){
		var url = $.trim($(".url").val());
		if(!url){
			layer.msg('请输入连接地址!');
			return false;
		}
		return true;
	}
	
	function initWebSocket(){
		ws = new WebSocket(ws_url);
		ws.onopen = function(evt) { 
			$("#connect").removeClass("btn-default").attr("disabled",false);
			$(".send").show();
			$(".connect").hide();
			heartCheck.start();
			sendJson("connect", "")
        }; 
        ws.onclose = function(evt) { 
        	layer.msg("断开连接！");
        }; 
        ws.onmessage = function(evt) { 
            heartCheck.reset();
            handle(JSON.parse(evt.data));
        }; 
        ws.onerror = function(evt) { 
        	var user=getCookie("QQ_TOKEN");
        	reconnect(user);
        }; 
	}
	
	function sendJson(type, content) {
		sendJson(type, content, null);
	}
	
	function sendJson(type, content, toUserId) {
		ws.send(JSON.stringify({
			id: $.cookie("user_id"),
			name: $.cookie("user_nickname"),
			type: type,
			content: content,
			toUserId: toUserId
		}));
	}
	
	function handle(data){
		if("-1" == data.type){
			layer.msg(data.content);
			$(".send").hide();
			$(".connect").show();
			return;
		}else if("0" == data.type){
			layer.msg("你好,"+data.name+"</br>欢迎来到wpfc聊天室...");
			$(".userlist .userNum").html(data.userList.length);
			if(data.userList.length > 1){
				var userStr = "";
				for(var i=0; i<data.userList.length; i++){
					var user = data.userList[i];
					if(data.id != user.id){
						userStr += '<li id="'+user.id+'" name="'+user.name+'">'+user.name+'</li>';
					}
				}
				$(".userlist ul").html(userStr);
			}
			initContent(data.id, data.contentList);
		}else if("1" == data.type){
			(!sel_userid || sel_userid == data.from) ? printOther(data) : countTipMsgNum(data);
		}else if("2" == data.type){
			var ils = $(".userList ul li");
			var flag = true;
			if(0 != ils.length){
				$(".userList ul li").each(function(){
					var id = $(this).attr("id");
					if(data.id == id){
						flag = false;
						return flag;
					}
				});
			}
			if(flag){
				$(".userList ul").append('<li id="'+data.id+'" name="'+data.name+'">'+data.name+'</li>');
				$(".userList .userNum").html(parseInt($(".userList .userNum").html())+1);
			}
			$("#main").append("<div class=\"login-item\"><span class=\"login-tip\">" + data.content + "</span></div>");
		}else if("3" == data.type){
			var ils = $(".userList ul li");
			if(0 != ils.length){
				$(".userList ul li").each(function(){
					var id = $(this).attr("id");
					if(data.id == id){
						$(this).remove();
						$(".userList .userNum").html(parseInt($(".userList .userNum").html())-1);
					}
				});
			}
		}else if("4" == data.type){
			//1v1聊天记录处理
		}else if("5" == data.type){
			(sel_userid && sel_userid == data.id) ? printOther(data) : countTipMsgNum(data);
		}
	}
	
	function initContent(id, contentList){
		if(contentList && contentList.length > 0){
			for(var i=0; i<contentList.length; i++){
				var content = contentList[i];
				if("1" == content.type){
					if(id == content.id){
						printOther(content);
					}else{
						printSelf(content);
					}
				}
			}
		}
	}
	
	function printOther(data){
		$("#main").append(
				"<div class=\"msg-item\"> " + 
        		"	<div><span class=\"name\">"+ data.from +"</span><span class=\"time\">" + 
        		new Date(data.sendTime).format("yyyy-MM-dd hh:mm:ss") + "</span></div>  " + 
        		"  	<div class=\"content\"> " + data.content + "</div>" +
        		"</div>");
		scroll();
	}
	
	function printSelf(content){
		$("#main").append(
				"<div class=\"msg-item\" style=\"float:right;\"> " 
				+ "<div style=\"text-align: right;\"><span class=\"time\">" 
				+ new Date().format("yyyy-MM-dd hh:mm:ss") 
				+ "</span><span class=\"name\" style=\"color:#1eab31;\">我<span></div>  " 
				+ "  	<div class=\"content\" style=\"float: right;\"> " 
				+ content + "</div>" + "</div>");
		scroll();
	}
	
	function scroll(){
		var e = document.getElementById("main");
		e.scrollTop=e.scrollHeight;
	}
	
	/**
	 * 统计消息提醒
	 * @param data
	 */
	function countTipMsgNum(data){
		if(data){
			$(".userlist ul li").each(function(){
				var _this = $(this);
				var id = _this.attr("id");
				if(id == data.id){
					var temp = _this.find("span");
					if(temp && 0 != temp.length){
						temp.html(parseInt(temp.html())+1);
					}else{
						_this.append("<span>1</span>");
					}
				}
			});
		}
	}
	
	function setCookie(ckey,cvalue,exdays){
		var exdate=new Date()
		exdate.setDate(exdate.getDate()+exdays)
		document.cookie=ckey+ "=" +escape(cvalue)+
		((exdays==null) ? "" : "; expires="+exdate.toGMTString())
	}
	
	function getCookie(cname){
		var name = cname + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i<ca.length; i++) {
			var c = ca[i].trim();
			if (c.indexOf(name)==0) return c.substring(name.length,c.length);
		}
		return "";
	}
	
	function checkCookie(){
		
		fun_getnickname(!0);
		
		/*var user=getCookie("QQ_TOKEN");
		if (user!=""){
			reconnect(user);
		}else{
			layer.prompt({title: '输入登录账号，并确认', formType: 1}, function(pass, index){
				if(pass){
					reconnect(pass);
					setCookie("QQ_TOKEN", pass, 30);
					layer.close(index);
				}
			});
		}*/
	}
	
	function reconnect(data) {
		if(3 == ws.readyState){
			if(lockReconnect) return;
			lockReconnect = true;
			//没连接上会一直重连，设置延迟避免请求过多
			setTimeout(function () {
				$("input.url").val("ws://localhost:8080/chat/"+data);
				connect();
				lockReconnect = false;
			}, 2000);
		}
    }
	
	/**
	 * 获取昵称
	 * @param a  true/false  是否真的修改昵称
	 * @returns  昵称
	 */
	function fun_getnickname(a) {
		$.cookie("user_id") && $.cookie("user_nickname") && $.cookie("room_name") && a ? 
		(ws || initWebSocket(), $(".footer").html($.cookie("user_nickname"))) : 
		$.getJSON("http://121.40.165.18:28001/Act/h_main.ashx?callback=?", {
			act: "getRanNick"
		}, function(b) {
			"OK" == b.state ? ($.cookie("user_id") || $.cookie("user_id", b.msg.id, {
				expires: 365
			}), $.cookie("room_name") || $.cookie("room_name", cur_rname, {
				expires: 365
			}), $.cookie("room_psw") || $.cookie("room_psw", cur_rpsw, {
				expires: 365
			}), a ? ($.cookie("user_nickname", b.msg.nickname, {
				expires: 365
			}), $(".footer").html(b.msg.nickname)) : 
				sendJson("chgname", b.msg.nickname), ws || initWebSocket()) : layer.msg(b.msg, {
				icon: 6
			})
		})
	}
	
	checkCookie();
	
	$(".userlistImage").bind("click", function(event){
		event.stopPropagation();
		$(".userlist").fadeIn(500);
	});
	
	$(document).bind('click',function(e){
		var ee = $(e.target);
		if(ee.closest(".userlist").length == 0){
			$(".userlist").fadeOut(500);
		}
	})
	
	/**
	 * 返回主聊天室
	 */
	$(".userlist-header").bind("click", function(){
		if(sel_userid){
			sel_userid = "";
			$(".msg_windows_title").html("消息窗口");
			$(".userlist ul li").removeClass("active");
			//清空main窗口
			$("#main").html("");
			//获取群聊记录 ，初始化页面
		}
	});
	
	$(document).on('click', ".userlist ul li", function(e){
		var _this = $(this);
		if(_this.hasClass("active")){
			return;
		}
		var userId = _this.attr("id");
		var userName = _this.attr("name");
		sendJson("one_records", userId);
		initOne2One(userId, userName);
		//清空消息提示数据
		_this.find("span").remove();
		_this.addClass("active").siblings().removeClass("active");
		$(".userlist").fadeOut(500);
	});
	
	function initOne2One(id, name){
		sel_userid = id;
		$(".msg_windows_title").html("与[<span>"+name+"</span>]的聊天记录");
		//清空主聊天记录
		$("#main").html("");
	}
	
});